package com.example.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.HashMap;
import java.util.HashSet;

/**
 * 本类用来演示:过滤器  由于没有进入web项目,所以没有filter接口,这是servlet中的,没有引入的话,
 * 网关Gateway(默认的服务器是netey)
 *过滤器模式:责任链模式
 *
 * @Author 胡英俊
 * @Date 2022/7/23 23:52
 */
@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();//响应头
       request.getURI().getPath();
       request.getHeaders();
       request.getMethod().name();


//        ServerHttpResponse response = exchange.getResponse();
////        设置编码
//        response.getHeaders().set("content-type","application/json;charset=utf-8");
//        HashMap<String, Object> map = new HashMap<>(4);
//        map.put("code", HttpStatus.UNAUTHORIZED.value());
//        map.put("msg","你未授权");
//        ObjectMapper objectMapper = new ObjectMapper();
////        把一个map转成字节
//        byte[] bytes = new byte[0];
//        try {
//            bytes = objectMapper.writeValueAsBytes(map);
//        } catch (JsonProcessingException e) {
//            e.printStackTrace();
//        }
////        通过buffer工厂将字节数组包装成一个数据包
//        DataBuffer wrap = response.bufferFactory().wrap(bytes);
//        return response.writeWith(Mono.just(wrap));
//
//        放行到下一个过滤器了
        return chain.filter(exchange);
    }

//    数值越小,越优先
    @Override
    public int getOrder() {
        return -1;
    }
}
